import 'dart:async';

import '../application.dart';
import 'api.dart';

class Login {
  var isLogging = false;
  var loggin = false;

  Completer<bool> loginComplete;
  Result result;

  Map<String, dynamic> userInfo;

  var agent = '';

  var token = "";
  var tokenTime = 0;
  var tokenExpire = 7200;
  var refreshToken = "";

  var _storeKey = 'login_token';

  constructor({agent = ''}) {
    this.agent = agent;
  }

  restoreToken() async {
    try {
      var data = Application.spref.get(_storeKey);
      if (data && data is List<String> && data.length == 4) {
        print('从缓存恢复登录数据');
        token = data[0];
        refreshToken = data[1];
        tokenTime = int.parse(data[2]);
        tokenExpire = int.parse(data[3]);

        await refresh();
      }
    } catch (e) {
      // Do something when catch error
    }
  }

  saveToken() async {
    if (token != '') {
      Application.spref.setStringList(_storeKey,
          [token, refreshToken, tokenTime.toString(), tokenExpire.toString()]);
    }
  }

  getToken() {
    return token;
  }

  clearLogin() async {
    token = '';
    Api.removeHeader('token');
    await Application.spref.remove(_storeKey);
  }

  /// 检查登录状态
  Future<bool> checkLogin() {
    if (isLogging) {
      print('已在登录');

      return loginComplete.future;
    }
    if (checkToken()) {
      return Future.value(true);
    } else {
      return Future.value(false);
    }
  }

  Future<bool> doLogin(username, password, {verify = ''}) {
    isLogging = true;
    loginComplete = Completer();
    print('执行登录操作');
    Api.post('auth/login', {
      'username': username,
      'password': password,
      'verify': verify
    }).then((json) {
      isLogging = false;
      result = json;
      if (json.code == 1) {
        loggin = true;
        setLogin(json.data);

        processQueue();
      } else {
        processQueue(success: false);
      }
    }).catchError((error) {
      isLogging = false;
      processQueue(success: false);
    });
    return loginComplete.future;
  }

  Future<dynamic> getUserInfo() {
    return Future.value({});
  }

  Future<dynamic> thirdLogin() {
    return Future(() {});
  }

  /// is_force:是否强制刷新
  Future<bool> refresh({isForce = false}) {
    if (isLogging) {
      print('已在刷新Token');
      return loginComplete.future;
    }

    if (isForce || !checkToken()) {
      print((isForce ? '强制' : '') +
          '刷新 token  AT ' +
          DateTime.now().toIso8601String());
      token = "";
      if (refreshToken != '') {
        loginComplete = Completer<bool>();
        isLogging = true;

        Api.post(
                'auth/refresh', {'refresh_token': refreshToken, 'scene': 'app'})
            .then((json) {
          isLogging = false;
          if (json.code == 1) {
            setLogin(json.data);
            processQueue();
          } else {
            clearLogin();
            processQueue(success: false);
          }
        }).catchError((error) {
          processQueue(success: false);
        });
        return loginComplete.future;
      } else {
        return checkLogin();
      }
    } else {
      print('不需刷新 token');
      return Future.value(true);
    }
  }

  //检查token是否有效
  checkToken() {
    if (token == '') {
      return false;
    }
    var nowTime = (DateTime.now().millisecondsSinceEpoch / 1000).ceil();
    if (tokenTime + tokenExpire - 30 <= nowTime) {
      return false;
    }

    return true;
  }

  setLogin(data) {
    token = data['token'];
    tokenTime = (DateTime.now().millisecondsSinceEpoch / 1000).floor();
    refreshToken = data['refresh_token'];
    tokenExpire = data['token_expire'];
    Api.addHeader('token', token);
    saveToken();
  }

  processQueue({success = true}) {
    if (success) {
      loginComplete.complete(true);
    } else {
      loginComplete
          .completeError({'code': result.code, 'message': result.message});
    }
  }
}
